package cn.swenty.backstage.framework.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import cn.swenty.backstage.framework.database.entity.Entity;

@Service
public class CommonService extends BaseService {
	
	
	private static Logger log = Logger.getLogger(CommonService.class);
	
	public List<? extends Entity> likeFind(String className,String value,String fields,int limit){
		try {
			
			Class c =Class.forName(className);
			Entity form = (Entity) c.newInstance();
			String sql = "";
			String [] fs = fields.split(",");
			for(int i=0;i<fs.length;i++){
				if(i==0){
					sql = " "+fs[i]+" like '%"+value+"%'";
				}else{
					sql+= " or "+fs[i]+" like '%"+value+"%'";
				}
			}
			form.put("$sql","(" +sql+")");
			
			return form.queryPage();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("find fail " + e.getMessage());
			throw new RuntimeException("save fail " + e.getMessage());
		} 
	}
	
	public Boolean isExist(String className,String field,String value_){
		try {
			Class c = Class.forName(className);
			Entity entity =  (Entity) c.newInstance();
			entity.put(field, value_);
			List<Entity> l = (List<Entity>) entity.query();
			if(l!=null&&l.size()>0){
				return true;
			}else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("find fail " + e.getMessage());
			throw new RuntimeException("save fail " + e.getMessage());
		} 
	}
	
	public Object getFieldValue(String className,String field,String value_,String showField){
		try {
			Class c = Class.forName(className);
			Entity e = (Entity) c.newInstance();
			e.put(field, value_);
			e = e.queryOne();
			return e!=null?e.get(showField):"";
		} catch (Exception e) {
			e.printStackTrace();
			log.error("find fail " + e.getMessage());
			throw new RuntimeException("save fail " + e.getMessage());
		} 
	}
	
	public List<Entity> queryList(String className,String key,String value){
		try {
			Class c = Class.forName(className);
			Entity entity = (Entity) c.newInstance();
			entity.put(key, value);
			return (List<Entity>) entity.query();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("find fail " + e.getMessage());
			throw new RuntimeException("save fail " + e.getMessage());
		} 
	}
	
}
